#include <queue>
#include <vector>
using namespace std;

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    explicit ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution
{
public:
    ListNode* mergeKLists(vector<ListNode*>& lists)
    {
        return merge(lists, 0, lists.size()-1);
    }

    ListNode* merge(vector<ListNode*>& lists, int left, int right)
    {
        if(left > right)
            return nullptr;
        if(left == right)
            return lists[left];
        int mid = (right+left)/2;

        ListNode* l1 = merge(lists, left, mid);
        ListNode* l2 = merge(lists, mid+1, right);

        return mergeTwoList(l1, l2);
    }

    ListNode* mergeTwoList(ListNode* l1, ListNode* l2)
    {
        if(l1 == nullptr)
            return l2;
        if(l2 == nullptr)
            return l1;
        ListNode* cur1 = l1;
        ListNode* cur2 = l2;
        ListNode* newhead = new ListNode(0);
        ListNode* prev = newhead;
        while(cur1 && cur2)
        {
            if(cur1->val > cur2->val)
            {
                prev->next = cur2;
                prev = prev->next;
                cur2 = cur2->next;
            }
            else
            {
                prev->next = cur1;
                prev = prev->next;
                cur1 = cur1->next;
            }
        }
        while(cur1)
        {
            prev->next = cur1;
            prev = prev->next;
            cur1 = cur1->next;
        }
        while(cur2)
        {
            prev->next = cur2;
            prev = prev->next;
            cur2 = cur2->next;
        }
        prev = newhead->next;
        delete newhead;
        return prev;
    }
};